﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataAccess;

public partial class Checkout : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected override void OnInit(EventArgs e)
    {
        // Chuyen huong qua trang Login neu nguoi dung chua dang nhap 
        Redirector.RedirectIfNotAuthenticated();
        base.OnInit(e);

        btnSumitOrder.Click += new EventHandler(btnSumitOrder_Click);
        btnConfirm.Click += new EventHandler(btnConfirm_Click);
    }
    // cac Product trong gio hang 
    private void PopulateControls()
    {
        grid.DataSource = ShoppingCart.Items();
        grid.DataBind();
        lblTotal.Text = ShoppingCart.TotalAmount().ToString("c");
    }

    void btnConfirm_Click(object sender, EventArgs e)
    {
        // sau khi nhap dia chi xong thi form nhap dia chi 
        phAddress.Visible = false;

        // hien phan thong tin da nhap de khach hang xac nhan 
        phConfirm.Visible = true;

        lblFullName.Text = LastName.Text + " " + FirstName.Text;
        lblEMail.Text = Email.Text;
        lblPhone.Text = Phone.Text.Replace("\n", "<br/>");
        lblAddress.Text = Address.Text.Replace("\n", "<br/>");

        // thong tin ve cac Product da mua 
        PopulateControls();
    }

    void btnSumitOrder_Click(object sender, EventArgs e)
    {
        // luu Order (don dat hang) vao CSDL 
        int orderNumber = ShoppingCart.CreateOrder(FirstName.Text,
                          LastName.Text, Email.Text, Phone.Text, Address.Text);

        phAddress.Visible = false;
        phConfirm.Visible = false;

        // Neu co loi xay ra thi hien thong bao loi 
        if (orderNumber <= 0)
        {
            phError.Visible = true;
        }
        else
        {
            // Luu so Order vao session de su dung trong trang OrderPlaced.aspx  
            // sau khi chuyen huong 
            Session["OrderNumber"] = orderNumber;
            Response.Redirect("~/OrderPlaced.aspx");
        }
    }
}